package com.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import com.pojo.po.YonghuPO;
import com.service.YonghuService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pojo.po.ConfigPO;
import com.pojo.po.EIException;
import com.service.ConfigService;
import com.utils.R;

import javax.servlet.http.HttpServletRequest;

/**
 * 上传文件映射表
 */
@RestController
@RequestMapping("file")
@SuppressWarnings({"unchecked","rawtypes"})
public class FileController{
	@Autowired
	private ConfigService configService;

	@Autowired
	private YonghuService yonghuService;
	/**
	 * 上传文件
	 */
	@RequestMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile file, String type, HttpServletRequest request) throws Exception {
		if (file.isEmpty())
		{
			throw new EIException("上传文件不能为空");
		}
		String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
		File path = new File(ResourceUtils.getURL("classpath:static").getPath());
		if(!path.exists())
		{
			path = new File("");
		}
		File upload = new File(path.getAbsolutePath(),"src/main/resources/static/upload/");
		if(!upload.exists())
		{
			upload.mkdirs();
		}

		//String fileName = new Date().getTime()+"."+fileExt;
		String fileName = file.getOriginalFilename().toString();
		File dest = new File(upload.getAbsolutePath()+"/"+fileName);
		file.transferTo(dest);
		if(StringUtils.isNotBlank(type) && type.equals("1"))
		{
			ConfigPO configEntity = configService.selectOne(new EntityWrapper<ConfigPO>().eq("name", "faceFile"));
			if(configEntity==null)
			{
				configEntity = new ConfigPO();
				configEntity.setName("faceFile");
				configEntity.setValue(fileName);
			}
			else
			{
				configEntity.setValue(fileName);
			}
			configService.insertOrUpdate(configEntity);
		}
		else
		{
			Long id = (Long)request.getSession().getAttribute("userId");
			YonghuPO user = yonghuService.selectById(id);
			if(user!=null)
			{
				String zhaopian="http://localhost:8080/springboot4c04d/upload/"+fileName;
				user.setZhaopian(zhaopian);
				yonghuService.insertOrUpdate(user);
			}
		}
		return R.ok().put("file", file.getName());
	}

	/**
	 * 下载文件
	 */
	@IgnoreAuth
	@RequestMapping("/download")
	public ResponseEntity<byte[]> download(@RequestParam String fileName) {
		try
		{
			//获取静态资源目录的路径，创建一个 File 对象 path 来表示静态资源目录
			File path = new File(ResourceUtils.getURL("classpath:static").getPath());
			if(!path.exists())
			{
				path = new File("");
			}
			File upload = new File(path.getAbsolutePath(),"/upload/");
			if(!upload.exists())
			{
				upload.mkdirs();
			}
			File file = new File(upload.getAbsolutePath()+"/"+fileName);
			if(file.exists())
			{
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
				headers.setContentDispositionFormData("attachment", fileName);
				return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR);
	}

}
